package water_qanxun_api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.json.JSONParser;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.web.bind.annotation.*;
import water_qanxun_api.config.MqttConfig;
import water_qanxun_api.controller.util.Code;
import water_qanxun_api.controller.util.Result;
import water_qanxun_api.domain.DevicesDataDomain;
import water_qanxun_api.service.DevicesDataService;
import water_qanxun_api.util.MqttServerUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController // 标记为控制类
@CrossOrigin // 解决跨域问题
@RequestMapping("devdata") // 指定请求路径
@Slf4j // 启用日志
public class DevicesDataController {
    @Autowired
    private DevicesDataService devicesDataService;
    @Resource
    private MqttConfig mqttConfig;
    
    @GetMapping("/get/{mac}")
    public Result getLatestDeviceDataByMac(@PathVariable("mac") String mac) {
        log.info("接收到数据:" + mac);
        // 根据mac地址使用MybatisPlus查询设备数据
        DevicesDataDomain data = devicesDataService.getLatestDeviceDataByMac(mac);
        return new Result(data, "数据接收成功");
    }
    
    /***
     * 拉取设备数据
     * @param mac 设备mac地址
     * @return 返回结果
     */
    @GetMapping("/pull/{mac}/{index}")
    public Result pull(@PathVariable("mac") String mac, @PathVariable("index") Integer index) {
        log.info("接收到数据:" + mac);
        // 根据mac地址使用MybatisPlus查询设备数据
        IPage<DevicesDataDomain> mapData = devicesDataService.queryDevicesDataByMac(mac, index);
        return new Result(mapData, "数据接收成功");
    }
    
    /***
     * 接收设备数据
     * @param data 接收到的数据
     * @return 返回结果
     */
    @PostMapping("/updata")
    public Result updata(@RequestBody String data) {
        log.info("接收到数据:" + data);
        // 将data字符串从JSON格式转换为Map
        Map<String, Object> mapData = null;
        try {
            mapData = (Map<String, Object>) new JSONParser(data).parseObject();
            String temp = (String) mapData.get("payload");
            String ID = (String) mapData.get("clientid");
            log.info("ID:" + ID);
            // timestamp
            String timestamp = mapData.get("timestamp").toString();
            log.info("timestamp:" + timestamp);
            // 把temp中的"\"去掉
            temp = temp.replace("\\", "");
            // 从字符串转成Map
            mapData = (Map<String, Object>) new JSONParser(temp).parseObject();
            log.info("转换后的数据:" + mapData);
            log.info("温度:" + mapData.get("temp"));
            log.info("湿度:" + mapData.get("humi"));
            log.info("光照:" + mapData.get("light"));
            log.info("土壤湿度:" + mapData.get("soilHumi"));
            // 判断temp和humi是否超过正常范围
            if(Integer.parseInt(mapData.get("temp").toString())>100){
                mapData.put("temp", -1);
            }
            if(Integer.parseInt(mapData.get("humi").toString())>100){
                mapData.put("humi", -1);
            }
            //将Map对象转换为JSON字符串
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(mapData);
            // 发布消息
//            devicesDataService.sendMqttMsg(ID, Code.OPEN_FAN);
            // 判断数值是否超标
            devicesDataService.isOverThreshold(mapData, ID);
            // 把字符串时间戳转换为Long类型
            Long timestampLong = Long.parseLong(timestamp);
            devicesDataService.insertData(ID, timestampLong, jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true, "数据接收成功");
    }
}
